package com.fuxi;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName ReentrantLockDemo
 * @Description TODO
 * @Author admin
 * @Date 2021/6/2 15:40
 * @Version 1.0
 **/
public class ReentrantLockDemo {
    
    private static Integer flag = 1;
    
    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Condition conditionA = lock.newCondition();
        Condition conditionB = lock.newCondition();
        Condition conditionC = lock.newCondition();
        
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 2; i++) {
                    try {
                        lock.lock();
                        while (flag != 1){
                            conditionA.await();
                        }
                        System.out.println("AAA");
                        flag = 2;
                        conditionB.signal();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        lock.unlock();
                    }
                }
            }
        });
    
        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 2; i++) {
                    try {
                        lock.lock();
                        while (flag != 2){
                            conditionB.await();
                        }
                        System.out.println("BBB");
                        flag = 3;
                        conditionC.signal();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        lock.unlock();
                    }
                }
            }
        });
    
        Thread threadC = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 2; i++) {
                    try {
                        lock.lock();
                        while (flag != 3){
                            conditionC.await();
                        }
                        System.out.println("CCC");
                        flag = 1;
                        conditionA.signal();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        lock.unlock();
                    }
                }
            }
        });
    
    
        threadA.start();
        threadB.start();
        threadC.start();
    }
    
}
